//
//  SAStoreManagementVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/6/7.
//

#import "SAStoreManagementVC.h"
#import "SAAddModifyStaffCell.h"
#import "SASystemStoreDetailAPI.h"
#import "SASystemStoreUpdateAPI.h"
#import "SAOverallSetting.h"
#import "ScanHelper.h"
#import "ZXingObjC.h"
#import "AppDelegate.h"
#import "QRCodePermissions.h"
#import "SAUpdateMerchantQrCodeAPI.h"

@interface SAStoreManagementVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *completeBtn;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *placeholderArr;
@property (nonatomic, strong) NSMutableArray *contentMarr;
@property (nonatomic, strong) SASystemStoreDetailAPI *systemStoreDetailAPI;
@property (nonatomic, strong) SASystemStoreUpdateAPI *systemStoreUpdateAPI;
@property (nonatomic, strong) UIImageView *codeImageV;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) SAUpdateMerchantQrCodeAPI *updateMerchantQrCodeAPI;

@end

@implementation SAStoreManagementVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemStoreDetailAPI == api) {
        NSDictionary *dic = data[@"data"];
        NSString *merchantName = dic[@"merchantName"];
        NSString *contactPhone = dic[@"contactPhone"];
        NSString *storeName = dic[@"storeName"];
        NSString *address = dic[@"address"];
        NSString *warnDesc = dic[@"warnDesc"];
        NSString *wxQrCode = dic[@"wxQrCode"];
        
        if (merchantName.length > 0) {
            self.contentMarr[0] = dic[@"merchantName"];
        }else {
            self.contentMarr[0] = @"";
        }
        if (contactPhone.length > 0) {
            self.contentMarr[1] = dic[@"contactPhone"];
        }else {
            self.contentMarr[1] = @"";
        }
        if (storeName.length > 0) {
            self.contentMarr[2] = dic[@"storeName"];
        }else {
            self.contentMarr[2] = @"";
        }
        if (address.length > 0) {
            self.contentMarr[3] = dic[@"address"];
        }else {
            self.contentMarr[3] = @"";
        }
        if (warnDesc.length > 0) {
            self.contentMarr[4] = dic[@"warnDesc"];
        }else {
            self.contentMarr[4] = @"";
        }
        if (wxQrCode.length > 0) {
            self.codeImageV.image = [self createCodeWithString:@"wxp://f2f0JpJvdm0fbMuXKYAJA-PTzbk8Y8bRdOQN08CUJ6cxnho" size:self.codeImageV.size CodeFomart:kBarcodeFormatQRCode];
            self.cancelBtn.hidden = NO;
        }else {
            self.codeImageV.image = [UIImage imageNamed:@"codeAdd"];
            self.cancelBtn.hidden = YES;
        }
        
        self.systemStoreUpdateAPI.merchantName = dic[@"merchantName"];
        self.systemStoreUpdateAPI.contactPhone = dic[@"contactPhone"];
        self.systemStoreUpdateAPI.storeName = dic[@"storeName"];
        self.systemStoreUpdateAPI.address = dic[@"address"];
        self.systemStoreUpdateAPI.warnDesc = dic[@"warnDesc"];
        self.updateMerchantQrCodeAPI.wxQrCode = dic[@"wxQrCode"];
        self.systemStoreUpdateAPI.storeId = [NSString stringWithFormat:@"%zd",[SAValueManger shareInStance].userInfo.storeInfo.storeId];
        
        [self.tableView reloadData];
    }else if (self.systemStoreUpdateAPI == api) {
        [SAValueManger shareInStance].userInfo.storeInfo.contactPhone = self.systemStoreUpdateAPI.contactPhone;
        [SAValueManger shareInStance].userInfo.storeName = self.systemStoreUpdateAPI.storeName;
        [SAValueManger shareInStance].userInfo.storeInfo.address = self.systemStoreUpdateAPI.address;
        [SAValueManger shareInStance].userInfo.storeInfo.warnDesc = self.systemStoreUpdateAPI.warnDesc;
        [self.updateMerchantQrCodeAPI submitForm:POST];
    }else if (self.updateMerchantQrCodeAPI == api) {
        [SAValueManger shareInStance].userInfo.storeInfo.wxQrCode = self.updateMerchantQrCodeAPI.wxQrCode;
        [Prompt popPromptViewWithMsg:@"保存成功" duration:2];
        [self.navigationController popViewControllerAnimated: YES];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {

}

#pragma mark - UITableView Delegate & DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAAddModifyStaffCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAAddModifyStaffCell"];
    [cell refreshManagementCellWithTitle:self.titleArr[indexPath.row] placeHolder:self.placeholderArr[indexPath.row] content:self.contentMarr[indexPath.row]];
    WeakSelf
    cell.textFieldBlock = ^(NSString *title, NSString *content) {
        if ([title isEqualToString:@"联系电话*"]) {
            weakSelf.systemStoreUpdateAPI.contactPhone = content;
        }else if ([title isEqualToString:@"店铺"]) {
            weakSelf.systemStoreUpdateAPI.storeName = content;
        }else if ([title isEqualToString:@"地址"]) {
            weakSelf.systemStoreUpdateAPI.address = content;
        }else if ([title isEqualToString:@"提醒"]) {
            weakSelf.systemStoreUpdateAPI.warnDesc = content;
        }
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

-(void)confirmationTapEvent {
    if (self.systemStoreUpdateAPI.contactPhone.length == 0) {
        [Prompt popPromptViewWithMsg:@"联系电话不能为空" duration:2];
        return;
    }
    [self.systemStoreUpdateAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)codeImageClick {
    if ([QRCodePermissions allowCamera]) {
        ScanQRViewController *pushVC = [[ScanHelper shareInstance] ScanVCWithStyle:weixinStyle qrResultCallBack:^(id result) {
            self.updateMerchantQrCodeAPI.wxQrCode = result;
            self.codeImageV.image = [self createCodeWithString:@"wxp://f2f0JpJvdm0fbMuXKYAJA-PTzbk8Y8bRdOQN08CUJ6cxnho" size:self.codeImageV.size CodeFomart:kBarcodeFormatQRCode];
            self.cancelBtn.hidden = NO;
            [self.navigationController popViewControllerAnimated:NO];
        }];
        [self.navigationController pushViewController:pushVC animated:YES];
    }else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请到设置隐私中开启本程序相机权限" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url options:nil completionHandler:^(BOOL success) {
                
            }];
        }];
        UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:action];
        [alert addAction:cancelAction];
        // 弹出对话框
        [self presentViewController:alert animated:YES completion:nil];
    }
}

-(void)clickedCancelBtn {
    self.codeImageV.image = [UIImage imageNamed:@"codeAdd"];
    self.updateMerchantQrCodeAPI.wxQrCode = @"";
    self.cancelBtn.hidden = YES;
}

#pragma mark - initUI

- (void)initUI {
    
    [self setNavigationItemBackBBIAndTitle:@"店铺管理"];
    [self setBgImage:nil];
    
    [self addRightViews:@[self.completeBtn]];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(kScaleNum(StatusHeight), 0, 0, 0));
    }];
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(60))];
    footView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableFooterView = footView;
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(kScaleNum(25), 0, kScaleNum(120), kScaleNum(60))];
    titleLab.font = kFont(15);
    titleLab.textColor = kBlackColor;
    titleLab.text = @"店铺二维码";
    [footView addSubview:titleLab];
    
    UIImageView *codeImageV = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth - kScaleNum(68), kScaleNum(7), kScaleNum(46), kScaleNum(46))];
    codeImageV.image = [UIImage imageNamed:@"codeAdd"];
    codeImageV.userInteractionEnabled = YES;
    [footView addSubview:codeImageV];
    UITapGestureRecognizer *codeImageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(codeImageClick)];
    [codeImageV addGestureRecognizer:codeImageTap];
    self.codeImageV = codeImageV;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setImage:[UIImage imageNamed:@"btn_cancle"] forState:UIControlStateNormal];
    cancelBtn.frame = SARectMake(kBaseScreenWidth - 40, 0, 24, 24);
    [cancelBtn addTarget:self action:@selector(clickedCancelBtn) forControlEvents:UIControlEventTouchUpInside];
//    cancelBtn.hidden = YES;
    self.cancelBtn = cancelBtn;
    [footView addSubview:cancelBtn];

    [self.systemStoreDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
}

- (UIImage*)createCodeWithString:(NSString*)str
                            size:(CGSize)size
                      CodeFomart:(ZXBarcodeFormat)format
{
    ZXMultiFormatWriter *writer = [[ZXMultiFormatWriter alloc] init];
    ZXBitMatrix *result = [writer encode:str format:format width:size.width height:size.width error:nil];
    ZXImage *image = [ZXImage imageWithMatrix:result];
    return [UIImage imageWithCGImage:image.cgimage];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kBgColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.bounces = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = kBgColor;
        [_tableView registerClass:[SAAddModifyStaffCell class] forCellReuseIdentifier:@"SAAddModifyStaffCell"];
    }
    return _tableView;
}

-(UIButton *)completeBtn {
    if (!_completeBtn) {
        _completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_completeBtn setTitle:@"完成" forState:UIControlStateNormal];
        _completeBtn.frame = SARectMake(254, 0, 85, 44);
        _completeBtn.titleLabel.font = kFont(16);
        [_completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_completeBtn addTarget:self action:@selector(confirmationTapEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    return _completeBtn;
}

- (NSArray *)titleArr {
    if (!_titleArr) {
        _titleArr = @[@"联系人*", @"联系电话*", @"店铺", @"地址", @"提醒"];
    }
    return _titleArr;
}

- (NSArray *)placeholderArr {
    if (!_placeholderArr) {
        _placeholderArr = @[@"", @"请输入联系电话", @"请输入店铺名称", @"请输入地址", @"*钱款、件数请当面点清,商店概不负责"];
    }
    return _placeholderArr;
}

- (NSMutableArray *)contentMarr {
    if (!_contentMarr) {
        _contentMarr = [NSMutableArray arrayWithObjects:@"", @"", @"", @"", @"", nil];
    }
    return _contentMarr;
}

-(SASystemStoreDetailAPI *)systemStoreDetailAPI {
    if (!_systemStoreDetailAPI) {
        _systemStoreDetailAPI = [SASystemStoreDetailAPI apiWithDelegate:self];
    }
    return _systemStoreDetailAPI;
}

-(SASystemStoreUpdateAPI *)systemStoreUpdateAPI {
    if (!_systemStoreUpdateAPI) {
        _systemStoreUpdateAPI = [SASystemStoreUpdateAPI apiWithDelegate:self];
    }
    return _systemStoreUpdateAPI;
}

-(SAUpdateMerchantQrCodeAPI *)updateMerchantQrCodeAPI {
    if (!_updateMerchantQrCodeAPI) {
        _updateMerchantQrCodeAPI = [SAUpdateMerchantQrCodeAPI apiWithDelegate:self];
    }
    return _updateMerchantQrCodeAPI;
}

@end
